package com.sohoappspot.sohosched.server.rpc;

import javax.jdo.Transaction;
import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import com.sohoappspot.sohosched.client.exception.NotLoggedInException;
import com.sohoappspot.sohosched.client.model.Customer;
import com.sohoappspot.sohosched.client.model.Service.AccessDeniedException;
import com.sohoappspot.sohosched.client.model.Service.CreateObjectResult;
import com.sohoappspot.sohosched.client.rpc.CustomerService;

import com.sohoappspot.sohosched.server.model.ModelParams;
import com.sohoappspot.sohosched.server.model.Store;
import com.sohoappspot.sohosched.server.model.DbCustomer;

public class CustomerServiceImpl extends RemoteServiceServlet implements
		CustomerService {

	protected final Store store = ModelParams.getStore();

	/*
	public Customer[] getCustomers() {
		Customer[] retCustomers = new Customer[3];
		retCustomers[0] = new Customer("Gene");
		retCustomers[1] = new Customer("Rebecca");
		retCustomers[2] = new Customer("Kim");
		return retCustomers;
	}
	*/

	public Customer[] getCustomers() throws NotLoggedInException {
		ModelParams.checkLoggedIn();
		Customer[] clientCustomers = null;
		final Store.Api api = store.getApi();
		List<DbCustomer> dbCustomers = api.getCustomers();
		try {
			clientCustomers = new Customer[dbCustomers.size()];
			int curEntry = 0;			
			for (DbCustomer eachCustomer : dbCustomers) {
				clientCustomers[curEntry] = new Customer(eachCustomer.getCustomerName());
				curEntry++;
			}
		} finally {
		}
		return clientCustomers; 
	}
	
	public void addCustomer(final String customerName)
			throws NotLoggedInException {
		final User user = getUser();
		final Store.Api api = store.getApi();
		try {
			final Store.Author me = api.getOrCreateNewAuthor(user);

			final DbCustomer customer = new DbCustomer(getUser(), customerName);
			api.saveCustomer(customer);

			final Transaction tx = api.begin();
			api.saveAuthor(me);
			tx.commit();
		} finally {
		}
	}

	private void checkLoggedIn() throws NotLoggedInException {
		ModelParams.checkLoggedIn();
	}

	private User getUser() {
		return ModelParams.getUser();
	}
}